package test.poi;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelToImage {

    public static void main(String[] args) {
        String inputFilePath = "D:/poi/test.xlsx";
        int sheetNum = 0; // 读取第一个sheet
        int width = 1024; // 图片宽度，可以根据需求调整
        int height = 768; // 图片高度，可以根据需求调整
        String outputFilePath = "D:/poi/test.png";
        try {
            Workbook wb = new XSSFWorkbook(inputFilePath);
            Sheet sheet = wb.getSheetAt(sheetNum);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            graphics.setPaintMode();
            graphics.clearRect(0, 0, width, height);
            Dimension size = new Dimension(width, height);
            float columnWidth = (float) size.width / sheet.getRow(0).getLastCellNum();
            int rowHeight = size.height / sheet.getLastRowNum();
            for (Row row : sheet) {
                for (Cell cell : row) {
                    int columnIndex = cell.getColumnIndex();
                    float x = columnWidth * columnIndex;
                    float y = rowHeight * row.getRowNum();
                    String cellValue = getCellValueAsString(cell);
                    graphics.drawString(cellValue, x, y + rowHeight);
                }
            }
            ImageIO.write(image, "png", new FileOutputStream(outputFilePath));
            graphics.dispose();
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else if (cell.getCellType() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else {
            return "";
        }
    }
}